package com.zfei.gfb.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

public class OssUtil {

    private static final Logger logger = LoggerFactory.getLogger(OssUtil.class);


    public static String upload(String localFilePath, String dir, String fileName) {

        InputStream inputStream;
        try {
            inputStream = new FileInputStream(localFilePath + fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            throw new StatusException(Status.FILE_NOT_FOUND);
        }
        return upload(inputStream, dir, fileName);
    }


    public static String upload(InputStream inputStream, String dir, String fileName) {

        if (fileName.length() > 100) {
            throw new StatusException(Status.INVALID_ARGUMENT, "文件名过长");
        }

        OSS ossClient = null;
        try {
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            String accessKeyId = "LTAI5tMWToPmBFjYMyyYHGmA";
            String accessKeySecret = "nC1bfpzdV0BZkCkupk7mjO5A561h0A";
            String bucket = "wpw-msy";

            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            String ossFilePath = dir + "/" + fileName;
            ossClient.putObject(bucket, ossFilePath, inputStream);
            Date expireDate = new Date(new Date().getTime() + 360L * 24 * 3600 * 1000);
            URL url = ossClient.generatePresignedUrl(bucket, ossFilePath, expireDate);
            return url.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;

    }

}
